package mygui


import (
	"reflect"
	"fyne.io/fyne/v2"
	//"fyne.io/fyne/v2/app"
	//"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/dialog"
	"os"
	"fmt"
	//"time"
	"encoding/csv"
	//"encoding/json"
	"io"
	"bufio"
	"errors"
	"bytes"
	//"github.com/flopp/go-findfont"
	"strings"
	//"reflect"
	"net/http"
    "io/ioutil"
    "net/url"
    "regexp"
    "strconv"
)



func indexOf(element string, data []string) (int) {
   for k, v := range data {
       if element == v {
           return k
       }
   }
   return -1
}

func obj_dir(obj interface{}){
    _dir := reflect.TypeOf(obj)
    for i := 0; i < _dir.NumMethod(); i++{
        fmt.Println(_dir.Method(i).Name)
    }
}



func http_data(u int, data ...string) (string, error) {

	mdata := make(url.Values)

	switch u {
		case 1:
			mdata["channel"] 	= []string{data[1]}
    		mdata["name"] 		= []string{data[0]}
    		mdata["set"] 		= []string{"1"}
			ret, err := post_form(mdata, MconfigIP + "compack")
			return ret, err
		case 2:
			mdata["channel"] 	= []string{data[1]}
    		mdata["name"] 		= []string{data[0]}
    		mdata["set"] 		= []string{"0"}
			ret, err:= post_form(mdata, MconfigIP + "compack")
			return ret, err
		case 3:
			mdata["channel"] 	= []string{data[1]}
    		mdata["game"] 		= []string{data[0]}
    		mdata["set"] 		= []string{"0"}
    		mdata["model"] 		= []string{"新增"}
			ret, err := post_form(mdata, MconfigIP + "see")
    		return ret, err
		case 4:
			mdata["old_game"] 	= []string{data[0]}
    		mdata["old_channel"]= []string{data[1]}
    		mdata["old_model"] 	= []string{data[2]}
    		mdata["new_game"] 	= []string{data[3]}
			mdata["new_channel"]= []string{data[4]}
    		mdata["new_model"] 	= []string{data[5]}
    		mdata["sum"] 		= []string{data[6]}
    		ret, err := post_form(mdata, MconfigIP + "set")
    		return ret, err
    	case 5:
    		mdata["game"] 		= []string{data[0]}
    		mdata["set"] 		= []string{"1"}
    		mdata["channel"]	= []string{data[1]}
    		mdata["model"]		= []string{data[2]}
    		ret, err := post_form(mdata, MconfigIP + "see")
    		return ret, err
	}
	return "", nil
}


func post_form(urldata url.Values, url string) (string, error) {
	fmt.Println(url,urldata)
    resp, err := http.PostForm(url,urldata)
    if err != nil {
    	fmt.Println("请求失败",err)
    	return "", errors.New("请求失败")

    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
    	fmt.Println("解析失败",err)
    	return "", errors.New("解析失败")
    }
    fmt.Println(string(body))
    return string(body), nil
}

func post_json(jsondata []byte, url string) (string, error) {
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsondata))
    if err != nil {
    	return "", errors.New("请求失败")
    } 
	client := &http.Client{}
	resp, err := client.Do(req)
    if err != nil {
    	return "", errors.New("请求失败")
    } 
	defer resp.Body.Close()
	//fmt.Println(resp.StatusCode,resp.Header,)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    	return "", errors.New("解析失败")
    } 
    defer client.CloseIdleConnections()
	return string(body), nil
}


type Headl struct {
    Token 		string 	`json:"token"`
    UserId   	int 	`json:"userId"`
    Permission  string

}

type Data_Headl struct {
    Login Payload_lgoin
    List  Payload_list
    Game  Payload_game
}

type Payload_lgoin struct {
    Username 	string `json:"username"` 
    Password   	string `json:"password"`
}

type Payload_list struct {
	PageNo		int `json:"pageNo"`
    PageSize	int `json:"pageSize"`
	
}

type Payload_game struct {
    GameId		int 	`json:"gameId"`
    Nums		string  `json:"nums"`
    Password	string  `json:"password"`
	
}

func post_updata(jsondata []byte, url string, mHeadl Headl) (string,error) {

	req, _ := http.NewRequest("POST",url,bytes.NewBuffer(jsondata))

	req.Header.Set("Accept", "application/json, text/plain, */*")
	req.Header.Set("Accept-Encoding","gzip, deflate, br")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
	req.Header.Set("Connection","keep-alive")
	req.Header.Set("Content-Type","application/json")
	req.Header.Set("Host", "sdkadmin.youxifan.com")
	req.Header.Set("Origin","http://boss.youxifan.com")
	req.Header.Set("Referer", "http://boss.youxifan.com/")
	req.Header.Set("sec-ch-ua", `" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"`)
	req.Header.Set("sec-ch-ua-mobile","?0")
	req.Header.Set("sec-ch-ua-platform", `"Windows"`)
	req.Header.Set("Sec-Fetch-Dest", "empty")
	req.Header.Set("Sec-Fetch-Mode","cors")
	req.Header.Set("Sec-Fetch-Site", "cross-site")
    //req.SetBasicAuth("anjiu", "JiuAnAdmin20190502")
	if len(mHeadl.Token) > 1 {
		req.Header.Set("token", mHeadl.Token)
		req.Header.Set("userId", strconv.Itoa(mHeadl.UserId))
		req.Header.Set("Content-Length", "26")
		/*
		cookie := &http.Cookie{
        	Name:   "Set-Cookie",
        	Value:  mHeadl.Permission,
    	}
		req.AddCookie(cookie)
		*/
	}else{
		req.Header.Set("Content-Length", "45")
	}
	
	req.Header.Set("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return "", errors.New("请求失败")
	}
	//fmt.Println("响应结果",resp.Status,resp.StatusCode,resp.Proto,resp.ProtoMajor,resp.ProtoMinor)
	defer resp.Body.Close()
	respByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    	return "", errors.New("解析失败")
    } 
    defer client.CloseIdleConnections()
    fmt.Println("request Headers:  ", req.Header)
    //if mHeadl.UserId == 0 {
    	//reg1 := regexp.MustCompile(`aliyungf_tc=(.*?);`)
    	//result1 := reg1.FindStringSubmatch(resp.Header["Set-Cookie"][0])
    	//mHeadl.Permission = resp.Header["Set-Cookie"][0]
    	//fmt.Println("result1 = ",result1[1])
    //}
    //fmt.Println("response Status:", resp.Header["Set-Cookie"][0])
	//fmt.Println("response Headers:", resp.Header)
	return string(respByte), nil

}


func url_QueryEscape(urls string) string {
	escapeUrl := url.QueryEscape(urls)
	escapeUrl = strings.Replace(escapeUrl, "%3A%2F%2F", "://", -1)
	escapeUrl = strings.Replace(escapeUrl, "%2F", "/", -1)
	return escapeUrl
}

func get_down(name string, urls string) bool {
	urls = url_QueryEscape(urls)
	req, _ := http.NewRequest("GET", urls, nil)
	req.Header.Set("Referer", "http://boss.youxifan.com/")
	req.Header.Set("sec-ch-ua-mobile", "?0")
	req.Header.Set("Upgrade-Insecure-Requests", "1")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36}")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return false
	}
	defer resp.Body.Close()
	respByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    	return false
    } 
    defer client.CloseIdleConnections()
    if WriteFile(name, respByte) == nil {
    	return true
    }
    return false
}


func WriteFile(filename string, data []byte) error {
    f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
    if err != nil {
        return err
    }
    n, err := f.Write(data)
    if err == nil && n < len(data) {
        err = io.ErrShortWrite
    }
    if err1 := f.Close(); err == nil {
        err = err1
    }
    return err
}


func re_get_time(s string, recom string) string {
    re := regexp.MustCompile(recom)
    result1 := re.FindStringSubmatch(s)
	return result1[1]
}


func open_file(readdata *[][]string, path string) bool {
	file, err := os.Open(path)
    if err != nil {
        return false
    }
    defer file.Close()

	strls := strings.Split(path, ".")

	switch strls[len(strls)-1] {
		case "txt":
			reader := bufio.NewReader(file)
    		for {
        		rec, err := reader.ReadString('\n')
        		if err == io.EOF {
            		break
        		}
        		strls = strings.Split(rec, ",")
        		*readdata = append(*readdata,strls)
    		}
		case "csv":
			csvReader := csv.NewReader(file)
    		for {
        		rec, err := csvReader.Read()
        		
        		if err == io.EOF {
            		break
        		}
        		if rec[2] != "账号" {
        			*readdata = append(*readdata,[]string{rec[2],rec[3]})
        		}
    		}
	}
    return true
}



func M_dialog(title string, message string, call func(bool), myWindow fyne.Window) {
	messg := dialog.NewConfirm(title,message,call,myWindow)
	messg.SetConfirmText("确定")
	messg.SetDismissText("取消")
	messg.Show()
}

func str_curt(str string) string {
	str = strings.Replace(str, " ", "", -1)
	return str
}